package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.BannerDao;
import com.leoman.entity.Banner;
import com.leoman.service.BannerService;
import com.leoman.utils.QiNiuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * BannerServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:57.
 */
@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private BannerDao bannerDao;

    @Override
    public List<Banner> findAll() {
        return bannerDao.findAll();
    }

    @Override
    public Page<Banner> find(int pageNum, int pageSize) {
        return bannerDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Banner> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Banner getById(int id) {
        return bannerDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        Banner banner = bannerDao.findOne(id);

        QiNiuUtils.delete(banner.getUrl());

        bannerDao.delete(id);
    }

    @Override
    public Banner create(Banner banner) {
        return bannerDao.save(banner);
    }

    @Override
    public Banner update(Banner banner) {
        return bannerDao.save(banner);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public List<Banner> iFindList() {
        return bannerDao.findAll();
    }

    @Override
    @Transactional
    public Integer saveBanner(Integer bannerId, Integer type, Integer position, String linkUrl, MultipartRequest multipartRequest) {
        try {
            Banner banner;

            if (null == bannerId) {
                banner = new Banner();
            } else {
                banner = bannerDao.findOne(bannerId);
                banner.setUpdateTime(System.currentTimeMillis());
            }

            if (type == 1) {
                position = 0;
            } else {
                Banner tempBanner = bannerDao.findOneByTypeAndPosition(type, position);

                if (null != tempBanner) {
                    banner = tempBanner;
                    banner.setUpdateTime(System.currentTimeMillis());
                }
            }

            MultipartFile url = multipartRequest.getFile("url");
            if (null != url && url.getSize() > 0) {
                if (null != banner.getId()) {
                    QiNiuUtils.delete(banner.getUrl());
                }
                banner.setUrl(QiNiuUtils.upload(url));
            }

            banner.setType(type);
            banner.setPosition(position);
            banner.setLinkUrl(linkUrl);

            bannerDao.save(banner);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Page<Banner> pageByParams(final Integer typeId, final Integer position, Integer pageNum, Integer pageSize) {
        return bannerDao.findAll(new Specification<Banner>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Banner> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (null != typeId) {
                    predicateList.add(cb.equal(root.get("type").as(Integer.class), typeId));
                }

                if (null != position) {
                    predicateList.add(cb.equal(root.get("position").as(Integer.class), position));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }
}